import { Book, BookDocument } from '@app/database/schemas/book.schema';
import { CategoryDocument } from '@app/database/schemas/category.schema';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

@Injectable()
export class BooksService {
  constructor(
    @InjectModel('Book') private readonly bookModel: Model<BookDocument>,
    @InjectModel('Category')
    private readonly categoryModel: Model<CategoryDocument>,
  ) {}

  create(book: Book) {
    return this.bookModel.create(book);
  }

  async findAll(query: any) {
    let { size, currentPage } = query || {};
    size = Number(size);
    currentPage = Number(currentPage);
    const res = await this.bookModel
      .find()
      .populate('categories')
      .skip((currentPage - 1) * size)
      .limit(size)
      .sort({ _id: -1 });
    const total = await this.bookModel.countDocuments();
    return {
      items: res,
      total,
    };
  }

  findOne(id: string) {
    return this.bookModel.findOne({ _id: id });
  }

  update(id: string, book: Book) {
    return this.bookModel.updateOne({ _id: id }, book);
  }

  remove(id: string) {
    return this.bookModel.deleteOne({ _id: id });
  }

  async option() {
    const categories = await this.categoryModel.find();
    return {
      title: '图书列表',
      descriptions: '显示和处理图书列表',
      items: [
        {
          label: '图书名称',
          prop: 'name',
          type: 'input',
        },
        {
          label: '作者',
          prop: 'author',
          type: 'input',
        },
        {
          label: '图书分类',
          prop: 'categories',
          keyName: 'name',
          type: 'multiple',
          items: categories,
        },
        {
          label: '图书单价',
          prop: 'price',
          type: 'input',
        },
        {
          label: '库存',
          prop: 'number',
          type: 'input',
        },
        {
          label: '图书封面',
          prop: 'image',
          type: 'img',
        },
        {
          label: '图书简介',
          prop: 'description',
          type: 'input',
        },
      ],
    };
  }
}
